#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from os import environ
import sys


class cmdSplit:
    def __init__(self, segs):
        self.segs = segs
        self.name = self.envs = self.opts = self.args = None
        self.split()

    def opts_nth(self, name, nth, defv=None):
        try:
            val = self.opts.get(name, [])[nth]
            if isinstance(defv, (int, bool, float)):
                return type(defv)(val)
            return val
        except:
            return defv

    def args_nth(self, name, nth, defv=None):
        try:
            val = self.args[nth]
            if isinstance(defv, (int, bool, float)):
                return type(defv)(val)
            return val
        except:
            return defv

    def split(self):
        """Split command line segements to command, envs, opts, args

        cmdline = input()
        segs = shlex.split(cmdline)
        name, envs, opts, args = args_split(segs)

        aaa=AAA bbb=BBB ccc --ddd=DDD --eee EEE --ddd hehe -- --fff FFF ggg kkk
        > envs: { aaa:AAA, bbb:BBB }
        > name: ccc
        > opts: [ {ddd:DDD}, {eee:EEE}, {ddd:hehe}, ... ]
        > args: [ --fff, FFF, ggg, kkk ]
        """

        segs = self.segs
        envs = {}
        name = None
        opts = {}
        args = []

        # Load global environ
        for k, v in environ.items():
            envs[k] = v

        segc = len(segs)
        if not segc:
            return

        i = 0

        # envs stage
        while i < segc:
            seg = segs[i]

            if seg.find("=") < 0:
                break

            env = seg.split("=", 1)
            envs[env[0]] = env[1]
            i += 1

        # name stage
        name = segs[i]
        i += 1

        # opts / segs
        while i < segc:
            seg = segs[i]
            i += 1

            # Everything after -- are args
            if seg == "--":
                # Eat all and quit
                args.extend(segs[i:])
                break

            if seg.startswith("--"):
                # --opt aaa --opt bbb arga argb ...

                subsegs = seg.split("=", 1)
                if len(subsegs) > 1:
                    # --lib=xxx.so

                    opt, val = subsegs
                else:
                    # --lib xxx.so

                    if i >= segc:
                        break

                    opt = seg
                    val = segs[i]

                    i += 1

                k = opt[2:]
                v = opts.get(k, [])
                v.append(val)
                opts[k] = v
            elif seg.startswith("-") and len(seg) > 1:
                # boolean opt:
                # cmd -EnableColor -mute
                # cmd -no-EnableColor -no-mute
                if seg.startswith("-no-") and len(seg) > 4:
                    k = seg[4:]
                    v = opts.get(k, [])
                    v.append(False)
                    opts[k] = v
                else:
                    k = seg[1:]
                    v = opts.get(k, [])
                    v.append(True)
                    opts[k] = v
            else:
                # cmd --aaa AAA xixi --bbb=BBB

                # xixi: args
                args.append(seg)

        self.name = name
        self.envs = envs
        self.opts = opts
        self.args = args


cmdparts = cmdSplit(sys.argv)
